/*
 * Copyright 2005-2013 rsico. All rights reserved.
 * Support: http://www.rsico.cn
 * License: http://www.rsico.cn/license
 */
package com.rzico.core.plugin.sharing;

import com.alibaba.fastjson.JSON;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysUser;
import com.rzico.core.model.PluginAttribute;
import com.rzico.core.model.SharingReceiver;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.core.plugin.SharingPlugin;
import com.rzico.util.MD5Utils;
import com.rzico.util.StringUtils;
import com.rzico.util.XMLUtils;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Plugin - 微信分账(普通商户/特约商户)
 * @author rsico Team
 * @version 3.0
 */
@Component("weixinSharingPlugin")
public class WeiXinSharingPlugin extends SharingPlugin {

	@Value("${weixin.appid}")
	private String wx_appid;
	@Value("${weixin.mchid}")
	private String wx_mchid;
	@Value("${weixin.mchSecret}")
	private String wx_mch_secret;

	@Override
	public String getName() {
		return "微信分账";
	}

	@Override
	public String getVersion() {
		return "1.0";
	}

	/**
	 * 作用：生成签名
	 */
	public String getSign(HashMap<String, Object> params, SysPlugin sysPlugin) throws Exception {
		String str = joinKeyValue(params,"&",true,"sign","key");
		// 签名步骤二：在string后加入KEY
		if ("1".equals(sysPlugin.getAttribute("method"))) {
			str += "&key=" + sysPlugin.getAttribute("key");
		} else {
			str += "&key=" + wx_mch_secret;
		}
		// 签名步骤三：MD5加密 签名步骤四：所有字符转为大写
		str = MD5Utils.getMD5Str(str).toUpperCase();
		return str;
	}

	@Override
	public Map<String, Object> sharing(SysPlugin sysPlugin, String sharingNo, String transaction_id, List<SharingReceiver> receivers,HttpServletRequest request) {

		HashMap<String, Object> packageParams = new HashMap<>();
		HashMap<String, Object> finalpackage = new HashMap<>();
		String createNoncestr = StringUtils.CreateNoncestr();

		if ("1".equals(sysPlugin.getAttribute("method"))) {
			packageParams.put("appid", sysPlugin.getAttribute("appid"));
			packageParams.put("mch_id", sysPlugin.getAttribute("mchid"));
		} else {
			packageParams.put("appid", wx_appid);
			packageParams.put("mch_id", wx_mchid);
			packageParams.put("sub_appid", sysPlugin.getAttribute("appid"));
			packageParams.put("sub_mch_id", sysPlugin.getAttribute("mchid"));
		}

		packageParams.put("nonce_str", createNoncestr);
		packageParams.put("out_trade_no", sharingNo);
		packageParams.put("transaction_id", transaction_id);

		// 这里写的金额为1 分到时修改
		packageParams.put("receivers", JSON.toJSONString(receivers));

		try {
			String sign = getSign(packageParams,sysPlugin);
			packageParams.put("sign", sign);


		} catch (Exception e) {
			finalpackage.put("return_code", "9999");
			finalpackage.put("error_msg", "设置异常");
			return finalpackage;
		}

		try {
			String resultXml = XMLUtils.mapToXml(packageParams);

			String respStr = post("https://api.mch.weixin.qq.com/secapi/pay/profitsharing",resultXml,createSSLHttpClient(sysPlugin,request));

			Map resultMap = XMLUtils.xmlToMap(respStr);
			String return_code = (String) resultMap.get("return_code");
			if (return_code.equals("SUCCESS")) {
				String result_code = (String) resultMap.get("result_code");
				if (result_code.equals("SUCCESS")) {
					finalpackage.put("return_code", "0000");
					finalpackage.put("error_msg","申请成功");
					finalpackage.put("tranSn", (String) resultMap.get("order_id"));
				} else {
					finalpackage.put("return_code", "0003");
					finalpackage.put("error_msg", (String) resultMap.get("err_code_des"));
				}

			} else {
				finalpackage.put("return_code", "0003");
				finalpackage.put("error_msg", (String) resultMap.get("return_msg"));

			}

		} catch (Exception e) {
			finalpackage.put("return_code", "9999");
			finalpackage.put("error_msg", "设置异常");
		}
		return finalpackage;

	}

	/**
	 * 查询分账结果  0000成功  9999处理中  其他的失败
	 */
	@Override
    public Map<String, Object> query(SysPlugin sysPlugin,String sharingNo,String transaction_id,HttpServletRequest request) {

		HashMap<String, Object> finalpackage = new HashMap<>();
		String createNoncestr = StringUtils.CreateNoncestr();
		HashMap<String, Object> parameterMap = new HashMap<String, Object>();
		if ("1".equals(sysPlugin.getAttribute("method"))) {
			parameterMap.put("appid", sysPlugin.getAttribute("appid"));
			parameterMap.put("mch_id", sysPlugin.getAttribute("mchid"));
		} else {
			parameterMap.put("appid", wx_appid);
			parameterMap.put("mch_id", wx_mchid);
			parameterMap.put("sub_appid", sysPlugin.getAttribute("appid"));
			parameterMap.put("sub_mch_id", sysPlugin.getAttribute("mchid"));
		}
		parameterMap.put("transaction_id",transaction_id);
		parameterMap.put("out_trade_no",sharingNo);
		parameterMap.put("nonce_str", createNoncestr);
		try {
			parameterMap.put("sign",getSign(parameterMap,sysPlugin));
		} catch (Exception e) {
			finalpackage.put("return_code", "0003");
			finalpackage.put("error_msg","签名出错");
			return finalpackage;
		}

		try {
			String xml = XMLUtils.mapToXml(parameterMap);
			String resultXml = post("https://api.mch.weixin.qq.com/pay/profitsharingquery",xml,createSSLHttpClient(sysPlugin,request));
			Map<String,Object> resultMap = XMLUtils.xmlToMap(resultXml);
			String return_code = (String) resultMap.get("return_code");
			if (return_code.equals("SUCCESS")) {
				String result = (String) resultMap.get("result_code");
				if ("SUCCESS".equals(result)) {
					String status = (String) resultMap.get("status");
					if (status.equals("FINISHED")) {
						finalpackage.put("return_code", "0000");
						finalpackage.put("error_msg","申请成功");
					} else if (status.equals("ACCEPTED")) {
						finalpackage.put("return_code", "0001");
						finalpackage.put("error_msg","受理成功");
					} else if (status.equals("PROCESSING")) {
						finalpackage.put("return_code", "0001");
						finalpackage.put("error_msg","等待处理");
					} else {
						finalpackage.put("return_code", "0003");
						finalpackage.put("error_msg", "分账失败");
					}
				} else  {
					String errCode = (String) resultMap.get("err_code");
					if ("ORDERNOTEXIST".equals(errCode)) {
						finalpackage.put("return_code", "0003");
						finalpackage.put("error_msg", (String) resultMap.get("err_code_des"));
					} else {
						finalpackage.put("return_code", "9999");
						finalpackage.put("error_msg", (String) resultMap.get("err_code_des"));
					}
				}
			} else
			{
				finalpackage.put("return_code", "9999");
				finalpackage.put("error_msg", (String) resultMap.get("return_msg"));
			}
		} catch (Exception e) {
			finalpackage.put("return_code", "9999");
			finalpackage.put("error_msg", "设置异常");
		}

		return finalpackage;
	}

}